﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BubbleFollow : MonoBehaviour
{
    /*
	 * List:
	 * 1.Bubble Fade In -done
	 * 2.Bubble random shake -done
	 * 3.Bubble Dynamic follow -done
	 * 4.Texture Flowing -done
	 * 5.Bubble Dancing
	 * */
    // Start is called before the first frame update
    [Header("Following")]
    public float FollowingStrength;
    public Transform Target;
    [Header("RandomShaking")]
    public float RandomShakingStrength;
    public float RandomShakingRate;
    [Header("TextureFlow")]
    public float TextureFlowingSpeed;
    Vector3 RotationVector;
    Color Transparent;
    Rigidbody rb;

    private void Awake()
    {
        //FadeIn
        rb = GetComponent<Rigidbody>();
        StartCoroutine(FadeIn());
        StartCoroutine(TextureFlow());
        StartCoroutine(BubbleTracking());
        StartCoroutine(BubbleRandomShaking());
    }

    // Update is called once per frame
    void Update()
    {
        if (Target.gameObject == null)
        {
            Destroy(gameObject);
        }
        gameObject.transform.Rotate(RotationVector * Time.deltaTime * TextureFlowingSpeed);
    }

    IEnumerator TextureFlow()
    {
        //self Rotation
        while (true)
        {
            yield return new WaitForSeconds(3f);
            RotationVector = new Vector3(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
        }
    }
    IEnumerator FadeIn()
    {
        while (true)
        {
            yield return new WaitForEndOfFrame();
            Transparent.a = Mathf.Lerp(Transparent.a, 0.6f, Time.deltaTime);
            if (Mathf.Abs(Transparent.a - 0.6f) <= 10e-5) break;
        }
    }
    IEnumerator BubbleTracking()
    {
        while (true)
        {
            yield return new WaitForEndOfFrame();
            //bubble tracing
            rb.AddForce((Target.position - transform.position) * FollowingStrength, ForceMode.Acceleration);
        }
    }
    IEnumerator BubbleRandomShaking()
    {
        while (true)
        {
            yield return new WaitForSeconds(RandomShakingRate);
            rb.AddForce(new Vector3(Random.Range(0, RandomShakingStrength), Random.Range(0, RandomShakingStrength), Random.Range(0, RandomShakingStrength)), ForceMode.Impulse);
        }
    }
}
